<template>
  <!-- 用户管理 -->
  <div class="app-container table-flex-wrapper">
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <!--<el-form-item>-->
        <!--<el-button size="mini" @click="handleAdd" type="primary">新增</el-button>-->
      <!--</el-form-item>-->
    </el-form>

    <el-table v-loading="loading" size="mini" :data="roleList" @selection-change="handleSelectionChange">
      <!--<el-table-column prop="id" type="hidden"></el-table-column>-->
      <el-table-column label="序号" type="index" width="70" align="center">
        <!--<template slot-scope="scope">-->
        <!--<span>{{scope.row.index}}</span>-->
        <!--</template>-->
      </el-table-column>
      <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
      <el-table-column prop="roleHaveUser" label="已有人员" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="operation" label="操作" align="center" min-width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" class="btn" @click="handleUpdate(scope.row)" v-hasPermi="['system:role:edit']">编辑</el-button>
          <el-button size="mini" class="btn white" type="primary" @click="deleteInfo(scope.row.roleId)" v-hasPermi="['system:role:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" class="d1" v-loading="addAndUpdateLoading">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small">
        <el-form-item label="角色名称" prop="userNo">
          <el-input v-model="form.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree :data="menuOptions" show-checkbox ref="menu" node-key="id" empty-text="加载中，请稍后" :props="defaultProps"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" size="small">确 定</el-button>
        <el-button @click="cancel" size="small">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listRole, getRole, addRole, updateRole, changeRoleStatus, delRole } from "@/api/system/role";
  import { treeselect as menuTreeselect, roleMenuTreeselect } from "@/api/system/menu";

  export default {
    name: "management",
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 总条数
        total: 0,
        // 角色表格数据
        operationList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层（数据权限）
        openDataScope: false,
        // 状态数据字典
        statusOptions: [],
        // 菜单列表
        menuOptions: [],
        // 角色表格数据
        roleList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          grade: undefined, // 用户等级
          keywords: undefined // 关键字
        },
        // 表单参数
        form: {
          roleName: "",
          roleKey: "",
          roleSort: 0
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 表单校验
        rules: {
          roleName: [{
            required: true,
            message: "角色名称不能为空",
            trigger: "blur"
          }],
          roleKey: [{
            required: true,
            message: "权限字符不能为空",
            trigger: "blur"
          }],
          roleSort: [{
            required: true,
            message: "角色顺序不能为空",
            trigger: "blur"
          }]
        },
        // 新增和修改时发送请求的遮罩层
        addAndUpdateLoading: false,
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      }).catch((error)=> {
        console.log(error);
      });
    },
    methods: {
      /**
       * 删除角色管理信息
       * @param id 角色管理id
       */
      deleteInfo(id) {
        let self = this;
         self.$confirm( "确认要删除该条信息吗?", "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
          })
          .then(function() {
            delRole(id).then((res)=>{
              if(res.code==200){
                self.msgSuccess(res.msg);
                self.getList();
              }else{
                self.msgError(res.msg);
              }
            }).catch(()=>{
              self.getList();
            });;
          })
          .then(() => {
            self.getList();
          })
          .catch(function(e) {
        });
      },
      /** 查询角色列表 */
      getList() {
        this.loading = true;
        listRole(this.addDateRange(this.queryParams, this.dateRange)).then(
          response => {
            console.log(response.rows);
            this.roleList = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        ).catch((error)=> {
          console.log(error);
        });
      },
      levelFormat(row, column) {
        return this.selectDictLabel(this.levelOptions, row.level);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        if (this.$refs.tree != undefined) {
          this.$refs.tree.setCheckedKeys([]);
        }
        this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.roleId);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getHalfCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.menu.getCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      /** 根据角色ID查询菜单树结构 */
      getRoleMenuTreeselect(roleId) {
        roleMenuTreeselect(roleId).then(response => {
          this.getMenuTreeselect();
          this.$refs.menu.setCheckedKeys(response.data);
        }).catch((error)=> {
          console.log(error);
        });
      },
      /** 查询菜单树结构 */
      getMenuTreeselect() {
        menuTreeselect().then(response => {
          this.menuOptions = response.data;
        }).catch((error)=> {
          console.log(error);
        });
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.getMenuTreeselect();
        this.open = true;
        this.title = "添加角色";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const roleId = row.roleId || this.ids;
        this.$nextTick(() => {
          this.getRoleMenuTreeselect(roleId);
        });
        getRole(roleId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改角色";
        }).catch((error)=> {
          console.log(error);
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.addAndUpdateLoading = true;
            if (this.form.roleId != undefined) {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              updateRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.addAndUpdateLoading = false;
              }).catch((error)=> {
                this.open = false;
                this.addAndUpdateLoading = false;
                console.log(error);
              });
            } else {
              this.form.menuIds = this.getMenuAllCheckedKeys();
              addRole(this.form).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
                this.addAndUpdateLoading = false;
              }).catch((error)=> {
                this.open = false;
                this.addAndUpdateLoading = false;
                console.log(error);
              });
            }
          }
        });
      },
      // 角色状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        var self = this;
        this.$confirm("确认要" + text + " " + row.roleName + " 角色吗?", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }).then(function() {
             changeRoleStatus(row.roleId, row.status).then(response => {
               if(response) {
                 if (response.code === 200) {
                   self.msgSuccess(response.msg);
                   self.getList();
                 } else {
                   self.msgError(response.msg);
                 }
               }else{
                 if (row.status == "0") {
                   row.status = "1";
                 } else {
                   row.status = "0";
                 }
               }
             }).catch((error)=> {
               self.msgError(error.msg);
             });;
          })
          .catch(function() {
            if (row.status == "0") {
              row.status = "1";
            } else {
              row.status = "0";
            }
          });
      }
    }
  };
</script>
<style lang="scss" scoped>
</style>
